--[[
		赠送系统，专门处理赠送
]]

local filename = "givesystem.lua"

local skynet = require "skynet"
local cluster = require "skynet.cluster"
require "skynet.manager"

local filelog = require "filelog"
local timetool = require "timetool"
local tabletool = require "tabletool"
local redisdao = require "redisdao"
require "pubenum"

local json = require "cjson"
json.encode_sparse_array(true,1,1)

local routerbase = require "routerbase"

local GiveSystem = routerbase:new()

--
--创建新的赠送
--
function GiveSystem.CMD.newgiving(rid, fields)
	rid = tonumber(rid)
	if not rid or type(fields) ~= "table" or not fields.recvrid then
		return false
	end
	
	--rid为0，改为系统rid
	if rid == 0 then rid = 1001 end
	
	local keyid = skynet.call(".nodeuuid", "lua", "getuuid")
	local status, result = skynet.pcall(cluster.call, "datanode", ".router", "insert_rk", rid, "rm_giverecord", keyid, fields)

	-- 通知有新赠送
	local agent = skynet.call(".mainnode", "lua", "cmd", "get_agent_by_rid", fields.recvrid)
	if agent then
		skynet.send(agent, "lua", "cmd", "notify_client", "givemoneyN", { })
	end
	
	--更新待领取赠送记录
	local key = "unclaimednum:" .. fields.recvrid
	local _,num = redisdao.query_data(".gmmqredis", "get", key)
	redisdao.query_data(".gmmqredis", "set", key, tonumber(num or 0) + 1)
	
	return keyid 
end

--
--获得赠送记录列表
--
function GiveSystem.CMD.getgiverecordlist(rid)
	rid = tonumber(rid) or 0
	
	local result = cluster.call("datanode", ".router", "select_rk", rid, "rm_giverecord")
	if not result or not result[2] then
		return {}
	end
	
	local giverecord_list = {}
	local waitdraw_state = EGiveMoneySate.EGIVEMONEY_STATE_WAIT_DRAW
	
	--只返回最近一周的数据，且不超过100条
	local limit_num = 100
	local cur_time = timetool.get_time()
	local cur_hour = tonumber( os.date("%H",cur_time))
	local cur_min = tonumber( os.date("%M",cur_time))
	local cur_sec = tonumber( os.date("%S",cur_time))
	local limit_time = cur_time - (6 * 86400 + cur_hour * 3600 + cur_min * 60 + cur_sec)
	
	local keyid_list = {}
	for keyid,item in pairs(result[2]) do
		if tonumber(item.create_time) > limit_time then
			table.insert(keyid_list, tonumber(keyid))
		elseif tonumber(item.current_state) == waitdraw_state then
			table.insert(keyid_list, tonumber(keyid))
		end
	end
	
	--插入满足条件的记录
	table.sort(keyid_list)
	for i = #keyid_list,1,-1 do
		local keyid = tostring(keyid_list[i])
		local item = result[2][keyid]
		if item then
			if (#giverecord_list < limit_num) 
			or (tonumber(item.current_state) == waitdraw_state) then
				local record_item = {
					recvrid = tonumber(item.recvrid),
					recvname = item.recvname,
					current_state = tonumber(item.current_state),
					give_value = tonumber(item.give_value),
					remark = item.remark,				
					give_time = tonumber(item.create_time),
					keyid = tonumber(keyid),
				}
				if record_item.current_state == EGiveMoneySate.EGIVEMONEY_STATE_WAIT_DRAW then
					record_item.curstate_time = tonumber(item.create_time)
				elseif record_item.current_state == EGiveMoneySate.EGIVEMONEY_STATE_HAD_DRAW then
					record_item.curstate_time = tonumber(item.get_time)
				elseif record_item.current_state == EGiveMoneySate.EGIVEMONEY_STATE_HAD_UNDO then
					record_item.curstate_time = tonumber(item.undo_time)
				end
				table.insert(giverecord_list, record_item)
			end
		end
	end
	
	return giverecord_list
end

--
--获取赠送领取列表
--
function GiveSystem.CMD.getgivedrawlist(rid)
	rid = tonumber(rid) or 0
	
	local givedraw_list = {}
	local waitdraw_state = EGiveMoneySate.EGIVEMONEY_STATE_WAIT_DRAW
		
	--只返回最近一周的数据，且不超过100条
	local limit_num = 100
	local cur_time = timetool.get_time()
	local cur_hour = tonumber( os.date("%H",cur_time))
	local cur_min = tonumber( os.date("%M",cur_time))
	local cur_sec = tonumber( os.date("%S",cur_time))
	local limit_time = cur_time - (6 * 86400 + cur_hour * 3600 + cur_min * 60 + cur_sec)
		
	--查询数据,直接从数据库查询
	local strhead = "select * from rm_giverecord where recvrid = " .. rid .. " and (create_time > " .. limit_time 
	local sqlstr = strhead .. " or current_state = " .. waitdraw_state .. " ) order by create_time desc "
	local status,resul_data = skynet.pcall(cluster.call, "datanode", ".router", "mysqlquery", 1, sqlstr)
	if status and resul_data and resul_data[1] ~= 0 and resul_data[2] then
		for _,item in pairs(resul_data[2]) do
			if (#givedraw_list < limit_num) 
			or (tonumber(item.current_state) == waitdraw_state) then
				local record_item = {
					sendrid = tonumber(item.rid),
					sendname = item.sendname,
					current_state = tonumber(item.current_state),
					give_value = tonumber(item.give_value),
					remark = item.remark,				
					give_time = tonumber(item.create_time),
					keyid = tonumber(item.keyid),
				}
				
				if record_item.current_state == EGiveMoneySate.EGIVEMONEY_STATE_WAIT_DRAW then
					record_item.curstate_time = tonumber(item.create_time)
				elseif record_item.current_state == EGiveMoneySate.EGIVEMONEY_STATE_HAD_DRAW then
					record_item.curstate_time = tonumber(item.get_time)
				elseif record_item.current_state == EGiveMoneySate.EGIVEMONEY_STATE_HAD_UNDO then
					record_item.curstate_time = tonumber(item.undo_time)
				end
				table.insert(givedraw_list, record_item)
			end
		end
	end
	
	return givedraw_list
end

--
--更新赠送记录	状态
--
function GiveSystem.CMD.update_givemoney_state(keyid, newstate, remark, undorid)
	newstate = tonumber(newstate) or 0
	keyid = tostring(keyid) or ""   --唯一id,数据库为int类型，但取出时已转换为string
	
	--查询数据
	local sqlstr = "select * from rm_giverecord where keyid = " .. keyid
	local status,result = skynet.pcall(cluster.call, "datanode", ".router", "mysqlquery", 1, sqlstr)
	if not status or not result or not result[2] or not result[2][1] then
		return false
	end

	--更新状态
	local update_list = {}
	local recorditem = result[2][1]
	local rid = tonumber(recorditem.rid)
	local curr_state = tonumber(recorditem.current_state)
	if newstate > curr_state and curr_state == EGiveMoneySate.EGIVEMONEY_STATE_WAIT_DRAW then
		recorditem.current_state = newstate
		update_list.current_state = recorditem.current_state
		if newstate == EGiveMoneySate.EGIVEMONEY_STATE_HAD_DRAW then    	--已领取
			recorditem.get_time = timetool.get_time()
			update_list.get_time = recorditem.get_time
		elseif newstate == EGiveMoneySate.EGIVEMONEY_STATE_HAD_UNDO then	--已撤销
			recorditem.undo_time = timetool.get_time()
			update_list.undo_time = recorditem.undo_time
			update_list.undorid = tonumber(undorid) or rid
			if remark then
				update_list.remark = tostring(remark)
			end
		end

		--更新赠送记录
		skynet.pcall(cluster.call, "datanode", ".router", "update_rk", rid, "rm_giverecord", keyid, update_list)
		
		--更新待领取赠送记录
		local key = "unclaimednum:" .. recorditem.recvrid
		local _,num = redisdao.query_data(".gmmqredis", "get", key)
		redisdao.query_data(".gmmqredis", "set", key, tonumber(num or 0) - 1)
		
		return {give_value = recorditem.give_value, give_type = recorditem.give_type, tradeid = recorditem.tradeid, create_time = recorditem.create_time}
	elseif curr_state == EGiveMoneySate.EGIVEMONEY_STATE_HAD_DRAW then
		return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "转账已被领取"}
	elseif curr_state == EGiveMoneySate.EGIVEMONEY_STATE_HAD_UNDO then
		return {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "转账已撤销"}
	end

	return false  
end

skynet.start(function()
	GiveSystem:start()
end)
